package cn.tx.service.impl;

import cn.tx.entity.PageResult;
import cn.tx.entity.QueryPageBean;
import cn.tx.mapper.SetMealDao;
import cn.tx.pojo.CheckGroup;
import cn.tx.pojo.InterTable;
import cn.tx.pojo.Setmeal;
import cn.tx.service.SetmealService;
import cn.tx.utils.FastDFSClient;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Snake Eyes
 * @PROJECT_NAME: health_parent
 * @DESCRIPTION:
 * @USER: 11647
 * @DATE: 2021/8/28 21:22
 * @Email: 1164763541@qq.com
 */
@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
    //从application.properties配置文件中取值
//    @Value("${tracker_server}")
    private String path = "http://192.168.25.133/";

//    @Value("${out_put_path}")//从属性文件读取输出目录的路径
    private String outputpath="E://htmls//health";
    //注入模板类
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Autowired
    private SetMealDao setMealDao;


    /**
     * @return
     * @author :11647
     * @date ：Created in 2021/8/28  21:23
     * @description：(描述) 上传文件
     * @modified By：11647
     * @version:
     */
    @Override
    public String upload(MultipartFile imgFile) {
        //文件上传相关代码

        //文件上传工具类
        FastDFSClient client = null;
        try {
            client = new FastDFSClient("classpath:config/fdfs_client.conf");

            //获取到上传文件的后缀名
            String filename = imgFile.getOriginalFilename();
            //获取后缀名
            String extName = filename.substring(filename.lastIndexOf(".") + 1);
            String s = client.uploadFile(imgFile.getBytes(), extName);
            String url = path + s;
            System.out.println("url：" + url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return path;
    }

    /**
     * @return
     * @author :11647
     * @date ：Created in 2021/8/29  15:15
     * @description：(描述) 分页查询方法
     * @modified By：11647
     * @version:
     */
    @Override
    public PageResult findPage(QueryPageBean pageBean) {
        Integer currentPage = pageBean.getCurrentPage();
        Integer pageSize = pageBean.getPageSize();
        String queryString = pageBean.getQueryString();
        //查询数据
        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> page = setMealDao.findPage(queryString);

        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * @return
     * @author :11647
     * @date ：Created in 2021/8/29  15:29
     * @description：(描述) 查询所有
     * @modified By：11647
     * @version:
     */
    @Override
    public List<Setmeal> findAll() {
        List<Setmeal> all = setMealDao.findAll();
        return all;
    }




    @Override
    public void save(Setmeal setmeal, Integer[] checkgroupIds) {
        setMealDao.save(setmeal);
        Integer id = setmeal.getId();
        Map<String, Integer> map = new HashMap();
        for (Integer checkgroupId : checkgroupIds) {
            //setmeal_id, checkgroup_id
            map.put("setmeal_id", id);
            map.put("checkgroup_id", checkgroupId);
            //中间表维护
            setMealDao.intTable(map);
        }
        //添加套餐之后生成对应的静态文件
        generateMobileStaticHtml();
    }

    /**
     * @return
     * @author :11647
     * @date ：Created in 2021/8/31  15:21
     * @description：(描述)查询检查套餐中 包含的所有检查项目id
     * @modified By：11647
     * @version:
     */
    @Override
    public Integer[] findIntTableId(Integer setmealid) {
        List<InterTable> intTableId = setMealDao.findIntTableId(setmealid);
        Integer[] ids = new Integer[intTableId.size()];
        for (int i = 0; i < intTableId.size(); i++) {
            ids[i] = intTableId.get(i).getCheckGroupId();
        }
        return ids;
    }

    /**
     * @return
     * @author :11647
     * @date ：Created in 2021/8/31  15:21
     * @description：(描述)删除方法
     * @modified By：11647
     * @version:
     */
    @Override
    public void delete(Integer id) {
        setMealDao.deleteInterTable(id);
        setMealDao.delete(id);
    }

    /**
     * @return
     * @author :11647
     * @date ：Created in 2021/8/31  15:21
     * @description：(描述)修改方法
     * @modified By：11647
     * @version:
     */
    @Override
    public void update(Integer[] checkgroupIds, Setmeal setmeal) {
        //删除中间表信息
        setMealDao.deleteInterTable(setmeal.getId());
        Map<String, Integer> map = new HashMap();
        for (int i = 0; i < checkgroupIds.length; i++) {
            map.put("setmeal_id", setmeal.getId());
            map.put("checkgroup_id", checkgroupIds[i]);
            setMealDao.intTable(map);
        }
        setMealDao.update(setmeal);


    }

    @Override
    public Setmeal findById(Integer id) {
        return setMealDao.findById(id);
    }

    /**
     * @author :11647
     * @date ：Created in 2021/9/11  13:31
     * @description：(描述) 查询体检名称
     * @modified By：11647
     * @version:
     */
    @Override
    public  List<Map<String, Object>>  findByName() {
        return setMealDao.findSetmealCount();
    }

    /**
     * @author :11647
     * @date ：Created in 2021/9/6  12:18
     * @description：(描述) 生成静态页面
     * @modified By：11647
     * @version:
     */
    public void generateHtml(String templateName, String htmlPageName, Map<String, Object> dataMap) {
        //获得freemak对象
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            //输出流
            out = new FileWriter(new File(outputpath + "//" + htmlPageName + ".html"));
            template.process(dataMap, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    //生成套餐列表静态页面
    public void generateMobileSetmealListHtml(List<Setmeal> list) {
        Map<String, Object> map = new HashMap<>();
        map.put("setmealList", list);
        generateHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }//mobile_setmeal_detail.ftl

    //生成套餐详情静态页面
    public void generateMobileSetmealDetailHtml(List<Setmeal> list) {

        for (Setmeal setmeal : list) {
            Map<String,Object> map = new HashMap<>();
            map.put("setmeal",setmeal.getCheckGroups());
            generateHtml("mobile_setmeal_detail.ftl","m_setmeal_datail"+setmeal.getId(),map);

        }
    }

    //生成静态页面
    public void generateMobileStaticHtml() {
        //查询所有数据
        List<Setmeal> all = setMealDao.findAll();
        //生成套餐静态页面
        generateMobileSetmealListHtml(all);
        //生成套餐详情静态页面
        generateMobileSetmealDetailHtml(all);

    }
}
